package org.ofbiz.framework.spring;

import java.util.Map;

import javolution.util.FastMap;

import org.ofbiz.base.util.Debug;
import org.ofbiz.framework.config.SpringEngineConfigUtil;
import org.ofbiz.framework.config.SpringInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GenericSpring implements SpringInterface {
	public static final String module = GenericSpring.class.getName();

	protected String springName = "default";
	protected static Map<String,Object> springCache = FastMap.newInstance();
	
	protected SpringContext springContext = null;
	public static SpringContext getSpringContext(String delegatorName){
        if (delegatorName == null) {
            delegatorName = "default";
            Debug.logWarning("Got a getSpring call with a null delegatorName, assuming default for the name.", module);
        }		
        SpringContext delegator = (SpringContext) springCache.get(delegatorName);
		if (delegator == null) {
            synchronized (GenericSpring.class) {
                // must check if null again as one of the blocked threads can
				// still enter
                delegator = (SpringContext) springCache.get(delegatorName);
                if (delegator == null) {
                    Debug.logInfo("Creating new spring context [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module);
                    
                    SpringInfo springInfo = SpringEngineConfigUtil.getSpringInfo(delegatorName);
                    if (springInfo == null) {
                        //throw new GenericSpringConfException("Cound not find an spring config with the name " + delegatorName);
                    	Debug.logError("Cound not find an spring config with the name " + delegatorName, module);
                    }                    
                    ApplicationContext ctx = new ClassPathXmlApplicationContext(springInfo.configFile);
                    delegator = new SpringContext(ctx);
                    if (delegator != null) {
                    	springCache.put(delegatorName, delegator);
                    } else {
                        Debug.logError("Could not create delegator with name " + delegatorName + ", constructor failed (got null value) not sure why/how.", module);
                    }
                }
            }		
		}
		return delegator;
	}

	public String getSpringName() {
		return springName;
	}
}

